//定义用户相关的仓库
import { defineStore } from "pinia";
import { reqCode, reqUserLogin } from "@/api/hospital/index";
import { SET_TOKEN, REMOVE_TOKEN } from "@/utils/user";
type userInfo = {
  name: string;
  token: string;
};
const useUserStore = defineStore("User", {
  state: () => {
    return {
      visible: false, //用于控制登录组件的dialog的显示与隐藏
      code: "", //存储验证码
      userInfo:
        JSON.parse(localStorage.getItem("USERINFO") as string) ||
        ({} as userInfo),
    };
  },
  actions: {
    //获取验证码的方法
    async getCode(phone: string) {
      let result: any = await reqCode(phone);
      if (result.data.code === 200) {
        this.code = result.data.data;
        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
    //用户手机号码登录的方法
    async userLogin(loginData: any) {
      let result: any = await reqUserLogin(loginData);
      if (result.data.code === 200) {
        this.userInfo = result.data.data;
        //本地存储持久化存储用户信息
        SET_TOKEN(JSON.stringify(this.userInfo));
        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
    //退出登陆方法
    logout() {
      //清空仓库的数据
      this.userInfo = { name: "", token: "" };
      //清空本地存储的数据
      REMOVE_TOKEN();
    },
    //查询微信扫码的接口（本地存储是否存储数据）
    queryState() {
      //开启定时器每隔一段时间去问本地是否都拥有用户信息
      let timer = setInterval(() => {
        //本地存储已经有数据：扫码成功
        if (localStorage.getItem("USERINFO")) {
          //关闭对话框
          this.visible = false;
          this.userInfo = JSON.parse(
            localStorage.getItem("USERINFO") as string
          );
          clearInterval(timer );
        }
      }, 1000);
    },
  },
  getters: {},
});
export default useUserStore;
